package controllers

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	// "test/model"
	// "strconv"
	_ "test/mysql"
)

type Row struct {
	Uid        int    `json:uid`
	Username   string `json:username`
	Departname string `json:departname`
	Created    string `json:created`
}
type Lists struct {
	Rows []Row `json:product`
}

type Data struct {
	Uid        int    `json:uid`
	Username   string `json:username`
	Departname string `json:departname`
	Created    string `json:created`
}
type Res struct {
	Status int    `json:status`
	Info   string `json:info`
	Msg    []Data `json:product`
}

/*
*return a json file
 */

func UserController(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
	w.Header().Set("content-type", "application/json")
	var m Res
	m.Status = 0
	m.Info = "ok"
	db, err := sql.Open("mysql", "root:123456@tcp(192.168.1.243:3306)/xuexi?charset=utf8")
	checkErr(err)
	if r.Method == "GET" { //select
		id := r.FormValue("id")
		// fmt.Printf(id)
		query, _ := db.Query("SELECT * FROM userinfo WHERE uid = " + id)
		column, _ := query.Columns()
		values := make([][]byte, len(column))     //values是每个列的值，这里获取到byte里
		scans := make([]interface{}, len(column)) //因为每次查询出来的列是不定长的，用len(column)定住当次查询的长度
		for i := range values {                   //让每一行数据都填充到[][]byte里面
			scans[i] = &values[i]
		}

		for query.Next() { //循环，让游标往下移动
			var uid int
			var username string
			var departname string
			var created string
			if err := query.Scan(scans...); err != nil { //query.Scan查询出来的不定长值放到scans[i] = &values[i],也就是每行都放在values里
				fmt.Println(err)
				return
			}
			err = query.Scan(&uid, &username, &departname, &created)
			checkErr(err)
			orderi := Data{Uid: uid, Username: username, Departname: departname, Created: created}
			fmt.Println(orderi)
			m.Msg = append(m.Msg, orderi)
		}
		db.Close()
		bytes, _ := json.Marshal(m)
		fmt.Printf("json:m,%s\n", bytes)
		// w.WriteHeader(http.StatusOK)
		// w.Write(bytes)
	} else if r.Method == "POST" { //add
		b, err := ioutil.ReadAll(r.Body)
		r.Body.Close()
		if err != nil {
			fmt.Printf("%s", err)
			return
		}
		// fmt.Printf("%s", b)
		var xxx = map[string]string{}
		err = json.Unmarshal([]byte(b), &xxx)
		username, _ := xxx["username"]
		departname, _ := xxx["departname"]
		created, _ := xxx["created"]
		// fmt.Printf(string(username))
		// fmt.Printf(string(departname))
		// fmt.Printf(string(created))
		stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
		checkErr(err)

		res, err := stmt.Exec(string(username), string(departname), string(created))
		// res, err := stmt.Exec("astaxi222e", "研发222部门", "2012-12-09")
		checkErr(err)

		id, err := res.LastInsertId()
		checkErr(err)
		db.Close()
		if id < 0 {
			m.Status = -1
			m.Info = "操作失败"
		}
	} else if r.Method == "PUT" { //update
		b, err := ioutil.ReadAll(r.Body)
		r.Body.Close()
		if err != nil {
			fmt.Printf("%s", err)
			return
		}
		// fmt.Printf("%s", b)
		var xxx = map[string]string{}
		err = json.Unmarshal([]byte(b), &xxx)
		username, _ := xxx["username"]
		departname, _ := xxx["departname"]
		created, _ := xxx["created"]
		uid, _ := xxx["id"]
		// fmt.Printf(string(username))
		// fmt.Printf(string(departname))
		// fmt.Printf(string(created))
		// fmt.Printf(uid)
		stmt, err := db.Prepare("update userinfo set username=?,departname=?,created=? where uid=?")
		checkErr(err)

		// res, err := stmt.Exec(string(username), string(departname), string(created), uid)
		res, err := stmt.Exec(string(username), string(departname), string(created), uid)
		// res, err := stmt.Exec("astaxi222e", "研发222部门", "2012-12-09")
		checkErr(err)
		num, err := res.RowsAffected()
		checkErr(err)
		fmt.Println(num)
		db.Close()
		if num <= 0 {
			m.Status = -1
			m.Info = "操作失败"
		}

	} else if r.Method == "DELETE" { //delete
		id := r.FormValue("id")
		fmt.Printf(id)

		stmt, err := db.Prepare("delete from userinfo where uid=?")
		checkErr(err)

		res, err := stmt.Exec(id)
		checkErr(err)

		affect, err := res.RowsAffected()
		checkErr(err)

		fmt.Println(affect)

		if affect <= 0 {
			m.Status = -1
			m.Info = "操作失败"
		}
	}
	db.Close()
	bytes, _ := json.Marshal(m)
	w.WriteHeader(http.StatusOK)
	w.Write(bytes)
}
